#!/usr/bin/env ruby

require 'tmpdir'

def build arch, output_dir
  sdk_path = if arch =~ /arm/ then %x[xcrun --sdk iphoneos --show-sdk-path].strip else %x[xcrun --sdk iphonesimulator --show-sdk-path].strip end

  cflags = "-Os -fembed-bitcode -Qunused-arguments -fPIC"
  cc = `/usr/bin/xcrun -f cc`.strip

  system "set -o pipefail && make clean && cmake -DENABLE_TESTING=Off -DENABLE_PROGRAMS=Off"

  #system "set -o pipefail && make clean && env CFLAGS=\"#{cflags}\" CC=\"#{cc}\" cmake -DCMAKE_OSX_DEPLOYMENT_TARGET=8.0 -DENABLE_TESTING=Off -DENABLE_PROGRAMS=Off -DCMAKE_OSX_SYSROOT=#{sdk_path} -DCMAKE_OSX_ARCHITECTURES=#{arch}"

  Dir.glob("**/*/flags.make").each do |path|
    text = File.read(path).gsub(/\-isysroot.+$/, "-isysroot \"#{sdk_path}\" -arch #{arch} -miphoneos-version-min=8.0 #{cflags}")
    File.open path, "w" do |f|
      f.write text
    end
  end

  abort "FAILED #{arch}!" unless system "make"

  FileUtils.mkdir "#{output_dir}/#{arch}" unless Dir.exists? "#{output_dir}/#{arch}"
  Dir.glob("library/*.a").each do |a|
    FileUtils.cp a, "#{output_dir}/#{arch}"
  end
end

output_dir = Dir.mktmpdir
at_exit do
  FileUtils.rm_rf output_dir
end

%w(arm64 armv7 i386 x86_64).each do |arch|
  build arch, output_dir
end

Dir.chdir output_dir do
  Dir.glob("*").each do |dir|
    Dir.chdir dir do
      system "libtool", "-static", *Dir.glob("*.a"), "-o", "libmbed.a"
    end
  end

  system "lipo", "-create", *Dir.glob("*/libmbed.a"), "-output", "libmbed.a"
end

lib = "#{output_dir}/libmbed.a"
headers = Dir.glob "include/mbedtls/*"

output_framework_dir = "mbedtls.framework"
FileUtils.rm_rf output_framework_dir if Dir.exists? output_framework_dir

FileUtils.mkdir output_framework_dir
FileUtils.cp lib, "#{output_framework_dir}/mbedtls"
FileUtils.mkdir "#{output_framework_dir}/Headers"

headers.each do |h|
  FileUtils.cp h, "#{output_framework_dir}/Headers"
end

puts "-> #{output_framework_dir}"
